package com.cyandpos.pad.common.ticketformat;

import android.text.TextUtils;


import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.posdata.CardCouponItem;
import com.cyandpos.pad.posdata.Goods;
import com.cyandpos.pad.posdata.OfferCoupon;
import com.cyandpos.pad.posdata.PayInfo;
import com.cyandpos.pad.posdata.Payment;
import com.cyandpos.pad.posdata.SubTicketItem;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.utils.DateUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.PayUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Administrator on 2017/5/17.
 */

public class TicketFormat {

    public static List<String> createTicketFormat(TicketInfo ticketInfo, boolean type, int nameinx) {
        List<String> mTicketList = new ArrayList<>();
        for (int i=0;i<ticketInfo.getSubTickets().size();i++){
            mTicketList.addAll(createHeadByTicket(ticketInfo, type,nameinx,i));//小票头信息
            mTicketList.addAll(createGoodsByTicket(ticketInfo,i));//小票商品信息
        }

        mTicketList.addAll(createPaymentByTicket(ticketInfo));//小票付款信息
        mTicketList.addAll(createMemberByTicket(ticketInfo));//小票会员信息
        mTicketList.addAll(createOfferCouponByTicket(ticketInfo));//返券信息
        mTicketList.addAll(createUserCouponByTicket(ticketInfo));//用券信息
        mTicketList.addAll(createUsedCZKByTicket(ticketInfo));//用储值卡信息
        mTicketList.addAll(createYHQCardByTicket(ticketInfo));//电子卡券付款信息
        mTicketList.addAll(createEndByTicket(ticketInfo));//小票尾部信息
        return mTicketList;
    }

    /**
     * 创建小票打印头部信息
     *
     * @return
     */

    public static List<String> createHeadByTicket(TicketInfo ticketInfo, boolean type, int nameinx,int i) {
        List<String> list = new ArrayList<>();
        list.add("");
        list.add("");
        list.add("欢迎光临"+ ErpCommonData.ticketHeader);
        if (ticketInfo.getOrderFunction()==1){
            list.add("订金单号：" + ticketInfo.getOrderNo());
        }
        if (nameinx==0){
            list.add("顾客联");//顾客联
        }else if (nameinx==1){
            list.add("商户联");//商户联
        }else {
        }

        if (type != false) {
            if (ticketInfo.getOrderFunction()==1){
                list.add("业务类型：重打订金单");
            }else {
                list.add("业务类型：重打小票");
            }
            list.add("补打时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()));

        } else {
            if (ticketInfo.getOrderFunction()==1){
                list.add("业务类型：订金单");

            }else {
                if (PayUtil.isReturnedTrade(ErpCommonData.ticketInfo)){
                    list.add("业务类型: 退货");
                }else{
                    if(ticketInfo.isFSTH()){
                        list.add("业务类型: 负数退货");
                    }else {
                        list.add("业务类型: 销售");
                    }
                }
            }
        }
        list.add("交易时间：" + ticketInfo.getOrderTime());
      //  list.add("收款台：" + ErpCommonData.sktno + "收款员：" + ticketInfo.getCasherInfo().getPersonCode());

        list.add("收款台：" + ErpCommonData.sktno + "收款员：" + ErpCommonData.loadConfig.getCashierCode());
        list.add("交易号：" + ticketInfo.getJlbh());
        if (ticketInfo.getOrderFunction()!=1) {
            list.add("订单号：" + ticketInfo.getOrderNo());
        }
        list.add(getStr());
        return list;
    }

    /***
     * 创建商品信息打印列表
     */
    public static List<String> createGoodsByTicket1(TicketInfo ticketInfo, int i) {
        List<String> list = new ArrayList<String>();
        for(SubTicketItem sub : ticketInfo.getSubTickets()){
            list.add("单价     数量   折扣    金额");  // .00=3个字符
            for(Goods g :sub.getGoodsList()){
                list.add(g.getName()+"["+g.getCode()+"]");
                String  stringsize= MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getPrice()))+g.getSaleCount()+MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getDiscount()))+MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getSaleMoney()) - MoneyUtils.getMoneyInt(g.getDiscount()));
                int countRegex = getWordCountRegex(stringsize);
                if (countRegex>=25)
                {
                    list.add((makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getPrice())),12,false)+makeStr(g.getSaleCount(),6,false)+
                            makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getDiscount())),12,false)));

                    list.add(makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getSaleMoney()) - MoneyUtils.getMoneyInt(g.getDiscount())),12,true));
                }else {
                    list.add((makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getPrice())),10,false)
                            +makeStr(g.getSaleCount(),4,false)
                            +makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getDiscount())),6,false)+
                            makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getSaleMoney()) - MoneyUtils.getMoneyInt(g.getDiscount())),12,false)));
                }
            }
        }
        return list;
    }

    /***
     * 创建商品信息打印列表
     */
    public static List<String> createGoodsByTicket(TicketInfo ticketInfo, int i) {
        List<String> list = new ArrayList<String>();

        list.add("单价     数量   折扣    金额");  // .00=3个字符
        for(Goods g :ticketInfo.getSubTickets().get(i).getGoodsList()){
            list.add(g.getName()+"["+g.getCode()+"]");
            String  stringsize=MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getPrice()))+g.getSaleCount()+MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getDiscount()))+MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getSaleMoney()) - MoneyUtils.getMoneyInt(g.getDiscount()));
            int countRegex = getWordCountRegex(stringsize);
            if (countRegex>=25)
            {
                list.add((makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getPrice())),12,false)+makeStr(g.getSaleCount(),6,false)+
                        makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getDiscount())),12,false)));

                list.add(makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getSaleMoney()) - MoneyUtils.getMoneyInt(g.getDiscount())),12,true));
            }else {
                list.add((makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getPrice())),10,false)
                        +makeStr(g.getSaleCount(),4,false)
                        +makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getDiscount())),6,false)+
                        makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(g.getSaleMoney()) - MoneyUtils.getMoneyInt(g.getDiscount())),12,false)));
            }


        }
        list.add("");
        return list;
    }


    /*
     * 会员信息打印
     *
     * @param ticketInfo
     */

    public static List<String> createMemberByTicket(TicketInfo ticketInfo) {
        List<String> list = new ArrayList<String>();
        if (ticketInfo.getMemberInfo() != null && ticketInfo.getMemberInfo().getMemberCardId() > 0) {
            list.add(getStr());
            list.add("卡号：" + ticketInfo.getMemberInfo().getMemberCardNo());
            list.add("本次积分：" + ticketInfo.getCent());
            list.add("累计积分：" + ticketInfo.getMemberInfo().getMemberCardValidCent());
        }
        return  list;
    }

     /*
     * 返券信息
     *
     * @param ticketInfo
     */

    public static List<String> createOfferCouponByTicket(TicketInfo ticketInfo) {
        List<String> list = new ArrayList<String>();
        if (ticketInfo.getOfferCouponList()!=null&&ticketInfo.getOfferCouponList().size() > 0) {
            list.add(getStr());
            list.add("返券信息：");
            if (ticketInfo.getOfferCouponList().get(0).getOfferMemberCardNo() != null &&!"".equals(ticketInfo.getOfferCouponList().get(0).getOfferMemberCardNo())&&!"null".equals(ticketInfo.getOfferCouponList().get(0).getOfferMemberCardNo())) {
                list.add("卡号：" + ticketInfo.getOfferCouponList().get(0).getOfferMemberCardNo());
            }
            for (OfferCoupon yhqItem : ticketInfo.getOfferCouponList()) {
                if(yhqItem.getCodeCoupons()!=null&&yhqItem.getCodeCoupons().size()>0){

                    for (OfferCoupon.CodeCoupon codeCoupon : yhqItem.getCodeCoupons()) {
                        list.add("名称：" + codeCoupon.getCodeCouponName());
                        list.add("金额：" + codeCoupon.getBalance());
                        list.add("有效期：" + codeCoupon.getDateValid());
                        if (yhqItem.getOfferMemberCardNo() != null &&!"".equals(yhqItem.getOfferMemberCardNo())&&!"null".equals(yhqItem.getOfferMemberCardNo())) {

                        }else {
                            list.add("券号：" + codeCoupon.getCouponCode());
                            if (codeCoupon.getNote1() != null && !"".equals(codeCoupon.getNote1()) || codeCoupon.getNote2() != null && !"".equals(codeCoupon.getNote2())) {
                                list.add(codeCoupon.getNote1() + "|" + codeCoupon.getNote2());
                            }
                        }
                    }
                }else {
                    list.add("优惠券名称：" + yhqItem.getCouponTypeName());
                    list.add("金额：" + yhqItem.getOfferMoney());
                    if (yhqItem.getNote1() != null && !"".equals(yhqItem.getNote1()) || yhqItem.getNote2() != null && !"".equals(yhqItem.getNote2())) {
                        list.add(yhqItem.getNote1() + "|" + yhqItem.getNote2());
                    }
                }
            }
        }
        return  list;
    }

    /*
     * 用券信息（卡券或者编码券）
     *
     * @param ticketInfo
     */

    public static List<String> createUserCouponByTicket(TicketInfo ticketInfo) {
        List<String> list = new ArrayList<String>();
        boolean isUsedCardCoupon = false;
        boolean isUsedCodedCoupon = false;
        for (Payment payment : ticketInfo.getPayList()) {
            if(payment.getPayType() == Payment.SKFS_YHQK){
                if(payment.getIsCoded()==0 && (payment.getPayInfoList()!=null && payment.getPayInfoList().size()>0)){
                    isUsedCardCoupon = true;
                }
                if(payment.getIsCoded()==1 && (payment.getPayInfoList()!=null && payment.getPayInfoList().size()>0)){
                    isUsedCodedCoupon = true;
                }
            }
        }
        if (isUsedCardCoupon ){
            list.add(getStr());
            list.add("用券信息：");
            for (Payment payment : ticketInfo.getPayList()) {
                if(payment.getPayType()==Payment.SKFS_YHQK && payment.getIsCoded()==0){
                    for(PayInfo payItem :payment.getPayInfoList()){
                        list.add("卡号："+payItem.getPay_cardNo());
                        list.add("名称："+payment.getPayName());
                        list.add("金额: " + payItem.getPay_amount());
                    }
                }
            }
        }

        if (isUsedCodedCoupon){
            list.add(getStr());
            list.add("编码券信息：");
            for (Payment payment : ticketInfo.getPayList()) {
                if(payment.getPayType()==Payment.SKFS_YHQK && payment.getIsCoded()==1){
                    for(PayInfo payItem :payment.getPayInfoList()){
                        list.add("券号："+payItem.getParam1());
                        list.add("金额: " + payItem.getPay_amount());
                    }
                }
            }
        }
        return list;
    }

    /*
     * 用储值卡
     *
     * @param ticketInfo
     */

    public static List<String> createUsedCZKByTicket(TicketInfo ticketInfo) {
        List<String> list = new ArrayList<String>();
        boolean isUsedCZK = false;
       if (ticketInfo.getPayList() != null && ticketInfo.getPayList().size() > 0) {
//            list.add(getStr());
            for (Payment payment : ticketInfo.getPayList()) {
                if(payment.getPayType() == Payment.SKFS_CZK){
                    isUsedCZK = true;
                }
            }
        }

        if(isUsedCZK){//储值卡
            list.add(getStr());
            list.add("储值卡信息：");
            for (Payment payment : ticketInfo.getPayList()) {
                if(payment.getPayType()==Payment.SKFS_CZK){
                    for(PayInfo payItem :payment.getPayInfoList()){
                        list.add("卡号："+payItem.getPay_cardNo());
                        list.add("名称："+payment.getPayName());
                        list.add("金额: " + payItem.getPay_amount());
//                        list.add("余额: " + payItem.get());
                    }
                }
            }
        }
        return list;
    }

     /*
     * 创建支付方式打印列表
     *
     * @param ticketInfo
     */

    public static List<String> createPaymentByTicket(TicketInfo ticketInfo) {
        List<String> list = new ArrayList<String>();
        if (ticketInfo.getPayList() != null && ticketInfo.getPayList().size() > 0) {
            list.add(getStr());
            for (Payment payment : ticketInfo.getPayList()) {
                String name = payment.getPayName().trim();
                list.add((makeStr(name,14,false)+makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(payment.getPayAmount())),9,false)));
            }
        }
        return list;
    }

    /**
     * 创建小票打印尾部信息
     *
     * @param ticketInfo
     * @return
     */
    public static List<String> createEndByTicket(TicketInfo ticketInfo) {
        List<String> list = new ArrayList<String>();
        list.add(getStr());
        list.add((makeStr("合计:" + MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(ticketInfo.getTotalAmount())),16,false)+makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(ticketInfo.getChangeAmount())),16,false)));
        list.add((makeStr("实收:" + MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(ticketInfo.getTotalAmount())),16,false)+makeStr(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(ticketInfo.getTotalDiscount())),16,false)));
        list.add(getStr());
        //list.add("欢迎再次光临商友POS");
        list.add(ErpCommonData.ticketEnd);
        if (ErpCommonData.printQrCode.equals("0")){ //0:打印二维码
            list.add("@@@"+ErpCommonData.QrCodecontent);
        }
        if (!ticketInfo.getOrderNo().isEmpty()){
            list.add("&&&"+ticketInfo.getOrderNo().toString());
        }
        list.add("  ");
        list.add("  ");
        list.add("  ");
        list.add("  ");
        return list;
    }


    /**
     * 电子优惠券打印信息
     * @param ticketInfo
     * @return
     */

    public static List<String> createYHQCardByTicket(TicketInfo ticketInfo) {
        List<String> list = new ArrayList<String>();

        if (ticketInfo.getCardCouponList()!= null ) {
            if (ticketInfo.getCardCouponList().size()> 0){
                list.add("");
                list.add("电子券：");
                for (CardCouponItem item : ticketInfo.getCardCouponList()) {
                    list.add("卡号："+item.getCardCode());
                    list.add("金额：" + MoneyUtils.getMoneyStr(item.getUsedMoney()) + " 余额：" +  MoneyUtils.getMoneyStr(item.getBalance()));
                }
            }
        }
        return list;
    }

    /**
     * 打印开单小票内容
     * @param mTicketInfo
     * @return
     */
    public static List<String> getBillingContent(TicketInfo mTicketInfo) {

        List<String> list = new ArrayList<>();
        list.add("欢迎光临"+ErpCommonData.ticketHeader);
        list.add("专柜预开单");
        list.add("");
        list.add("收款台：" + ErpCommonData.sktno);
        list.add("订单号：" + mTicketInfo.getOrderNo());
        list.add("营业员：" + mTicketInfo.getSubTickets().get(0).getPersonInfo().getPersonName());
        list.add("专柜：" + mTicketInfo.getSubTickets().get(0).getPersonInfo().getPersonDeptName());
        if (mTicketInfo.getMemberInfo() != null && mTicketInfo.getMemberInfo().getMemberCardId() > 0) {
            list.add("会员：" + mTicketInfo.getMemberInfo().getMemberName());
            list.add("会员类型：" + mTicketInfo.getMemberInfo().getMemberCardTypeName());
            list.add("会员卡号：" + mTicketInfo.getMemberInfo().getMemberCardNo());

        }
        list.add("日期：" + DateUtils.getCurrentTime());
        for (Goods goods : mTicketInfo.getSubTickets().get(0).getGoodsList()) {
            list.add(getStr());
            if (!TextUtils.isEmpty(goods.getCode()))
                list.add("商品码：" + goods.getCode());
            else
                list.add("商品条码：" + goods.getBarCode());

            list.add("零售价：  " + goods.getPrice());
            list.add("商品名称：" + goods.getName());
            list.add("商品数量：" + goods.getSaleCount());
            list.add("折扣金额：" + goods.getDiscount());
        }

        list.add(getStr());
        list.add("合计件数：" + mTicketInfo.getSubTickets().get(0).getTotalCount()
                + "		合计金额：" + (MoneyUtils.getMoneyStr(mTicketInfo.getSubTickets().get(0).getTotalMoney())));
        list.add(getStr());
        list.add("此小票为预开单小票");
        list.add("请到收款台或者最后消费的柜台支付");
        list.add("  ");
        return list;

    }


    //格式化
    public static String makeStr(String str, int length, boolean isLeft)
    {
        int count = getWordCountRegex(str);
        if(count < length)
        {
            if(isLeft)//右对齐
                str = Padding(" ",length-count) + str;
            else
                str = str+ Padding(" ",length-count);
        }
        return  str ;

    }

    //对汉字测试长度
    public static int getWordCountRegex(String s)
    {
        s = s.replaceAll("[^\\x00-\\xff]", "**");
        int length = s.length();
        return length;
    }
    //补充长度
    public static String Padding(String pad, int len)
    {
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<=len;i++){
            sb.append(pad);

        }
        return  sb.toString() ;
    }




    public static String getStr()
    {
        return "--------------------------------";
    }



    /**
     * 创建小票打印头部信息
     *
     * @return
     */

    public static List<String> createGuaDanTicket(String number) {
        List<String> list = new ArrayList<>();
        list.add("");
        list.add("挂单小票" );
        list.add(getStr());
        list.add("订单后六位" + number);
        list.add("挂单时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()));
        list.add("");
        list.add(getStr());
        list.add("备注:");
        list.add("请妥善保存好当前小票");
        list.add("");
        return list;
    }


}
